InsIssueReceive = new Object();

InsIssueReceive.getFieldSet1 = function() {


	Ext.create('Ext.data.Store', {
		fields : [ {	name : 'id',			type : 'int',	},
		           {	name : 'dealCode',		type : 'string'	},
		           {	name : 'type',			type : 'string'	},
		           {	name : 'maturityDate',	type : 'date',	dateFormat : 'c'	},
		           {	name : 'value',			type : 'string'	},
		           {	name : 'whtCertStatus',	type : 'string'	}
		         ],
		storeId:'insIssueReceiveDealsStore',

	});
	


	var insTransStore = Ext.create('Ext.data.Store', {
		fields : [ {	name : 'operation',		type : 'string'		} ],
		data : [ 
		         {	"operation" : "Collateral-IN"			},
		         {	"operation" : "Collateral-OUT"			},
		         {	"operation" : "Exchange"				},
		         {	"operation" : "Withhold Certificate"	}
		       ]
	});
	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Basic',
		defaults : {
			anchor : '100%'
		},
		items : [
		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ Ext.create('Ext.form.ComboBox', {
				name : 'transType',
				id:'newInsIssueTrType',
				fieldLabel : 'Transaction Type',
				store : insTransStore,
				allowBlank : false,
				disabled:true,
				flex : 1,
				padding : '0 20px 0 0',
				valueField : 'operation',
				queryMode : 'local',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{operation}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{operation}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {					
							var comboDeal = Ext.ComponentQuery.query('#insIssueDealCombo')[0];
							
							Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').clearFilter(true);
							
							if(combo.getValue()==='Collateral-IN'){
								Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').filter([
								                     Ext.create('Ext.util.Filter', {filterFn: function(item) { return (item.get("type")==='PURCH'||item.get("type")==='RREPO'); },root: 'data' })
										          ]);
								Ext.ComponentMgr.get('insIssueNewColField').disable();
								Ext.ComponentMgr.get('insIssueWithholdingCert').disable();
								Ext.ComponentMgr.get('insIssueRepoCollateralPanel').enable();
								
							}else if(combo.getValue()==='Collateral-OUT'){
								Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').filter([
								                     Ext.create('Ext.util.Filter', {filterFn: function(item) { return (item.get("type")==='SALE'||item.get("type")==='REPO'); }, root: 'data' })
										          ]);	
								Ext.ComponentMgr.get('insIssueNewColField').disable();
								Ext.ComponentMgr.get('insIssueWithholdingCert').disable();
								Ext.ComponentMgr.get('insIssueRepoCollateralPanel').enable();
								
							}else if(combo.getValue()==='Exchange'){
								Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').filter([
								                     Ext.create('Ext.util.Filter', {filterFn: function(item) { return (item.get("type")==='RREPO'||item.get("type")==='REPO'); },root: 'data' })
										          ]);	
								Ext.ComponentMgr.get('insIssueNewColField').enable();
								Ext.ComponentMgr.get('insIssueWithholdingCert').disable();
								Ext.ComponentMgr.get('insIssueRepoCollateralPanel').enable();
								
							}else if(combo.getValue()==='Withhold Certificate'){
								Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').clearFilter();
								Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').filter([
								             								                     Ext.create('Ext.util.Filter', {filterFn: function(item) { return (item.get("type")!=='TTT'); },root: 'data' })
								             										          ]);
								console.log('clerfilter');
								Ext.ComponentMgr.get('insIssueNewColField').disable();
								Ext.ComponentMgr.get('insIssueWithholdingCert').enable();
								Ext.ComponentMgr.get('insIssueRepoCollateralPanel').disable();
								
							}else{
								Ext.MessageBox.alert('Error', 'Invalid Transaction Type.');
							}
							comboDeal.clearValue();
						}
					}
				}
			}), Ext.create('Ext.form.ComboBox', {
				name : 'dealCode',
				id : 'insIssueDealCombo',
				fieldLabel : 'Deal Code',
				store : Ext.data.StoreManager.lookup('insIssueReceiveDealsStore'),
				flex : 1,
				padding : '0 5px 0 0',
				valueField : 'dealCode',
				queryMode : 'local',
				allowBlank : false,
				disabled:true,
				msgTarget : 'under',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item"><b>{dealCode}</b> - {type}<br/></div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{dealCode}', '</tpl>'),
				listeners : {
					select : {
						fn : function(combo, value) {
							var lblMaturityDate = Ext.ComponentQuery.query('#insIssueMatDtLbl')[0];
							var lblDealValue = Ext.ComponentQuery.query('#insIssueDealValLbl')[0];							
							var trTypeCmb = Ext.ComponentQuery.query('#newInsIssueTrType')[0];
							
							Ext.data.StoreManager.lookup('tempCollateralStore').removeAll();

							var matdate = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('maturityDate');
							if(matdate!=null){
								if (matdate < new Date()) {
									lblMaturityDate.setText('Deal Matured on '.concat(Ext.Date.format(matdate, 'd-m-Y')));
								} else {
									lblMaturityDate.setText('Deal Maturity : '.concat(Ext.Date.format(matdate, 'd-m-Y')));
								}
							}
							lblMaturityDate.show();
							
							var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('value');
							dealVal= Ext.util.Format.number(dealVal, '0,000.00');
							lblDealValue.setText('\nDeal Value: '+dealVal);
							lblDealValue.show();
							
							Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').removeAll();
							Ext.ComponentQuery.query('#insIssueInstrumentType')[0].clearValue();
							Ext.data.StoreManager.lookup('insIssueReceiveInsStore').removeAll();
							Ext.ComponentQuery.query('#insIssueInsNo')[0].clearValue();
							Ext.ComponentQuery.query('#insIssueIssuer')[0].clearValue();
							Ext.ComponentQuery.query('#insIssuePrimDealer')[0].clearValue();
							Ext.ComponentQuery.query('#insIssueColMatDate')[0].reset();
							var valField = Ext.ComponentQuery.query('#insIssueInsValue')[0];
							valField.reset();
							
							var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('type');
							
							var whtCertStatus = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('whtCertStatus');
							if (whtCertStatus === 'No') {									
								Ext.ComponentQuery.query('#insIssueWithholdNo')[0].setValue(true);
							} else if(whtCertStatus === 'NotReceived'){
								Ext.ComponentQuery.query('#insIssueWithholdNotReceived')[0].setValue(true);
							} else if(whtCertStatus === 'Received'){
								Ext.ComponentQuery.query('#insIssueWithholdReceived')[0].setValue(true);
							}else{
								if(trTypeCmb.getValue()==="Withhold Certificate"){
									Ext.Msg.alert("Error", "Data Corrupted.");
								}															
							}
							
							if(trTypeCmb.getValue()==null){
								Ext.MessageBox.alert('Error', 'Please Select a Transaction Type.');
							}else if(trTypeCmb.getValue()==='Withhold Certificate'){
								if (whtCertStatus === 'No') {
									Ext.ComponentMgr.get('insIssueWithholdingCert').disable();
								} else{
									Ext.ComponentMgr.get('insIssueWithholdingCert').enable();
								}	
							}else{
								if (dealType === 'REPO' || dealType === 'RREPO') {
									Ext.ComponentMgr.get('insIssueNewColField').enable();
									if(dealType === 'RREPO'){
										valField.enable();
									}else if(dealType === 'REPO'){
										valField.disable();
									}
									
									Ext.Ajax.request({
										url : 'FundInsTypeForDealType.action',
										params : {
											queryOne : combo.getValue(),
											queryTwo : dealType,
										},
										success : function(response) {
											var objInsType = Ext.decode(response.responseText);
											var arrayLength = objInsType.insTypes.length;
											for (var i = 0; i < arrayLength; i++) {
												Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').add(
											    		{
											    			id			:	objInsType.insTypes[i].id,
											    			type		:	objInsType.insTypes[i].instrumentName,
											    			listed		:	objInsType.insTypes[i].listed,
											    			issuer		:	objInsType.insTypes[i].istrumentType,
											    			scripts		:	objInsType.insTypes[i].scripts,
											    			denominal:	objInsType.insTypes[i].denominals,
											    			
											    		});
											}
										}
									});
									
									Ext.Ajax.request({
										url : 'getCollaterals.action',
										params : {
											queryOne : Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('dealCode'),
											queryTwo : dealType,
										},
										success : function(response) {
											var objIns = Ext.decode(response.responseText);
											if(objIns.insList!=null){
												var arrayLength = objIns.insList.length;
												for (var i = 0; i < arrayLength; i++) {
													Ext.data.StoreManager.lookup('insIssueReceiveInsStore').add(
												    		{
												    			id			:	objIns.insList[i].id,
												    			code		:	objIns.insList[i].instrumentCode,
												    			type		:	objIns.insList[i].instrumentType.instrumentName,
												    			issuer		:	objIns.insList[i].issuer.code,
												    			value		:	Ext.util.Format.number(objIns.insList[i].instrumentValue, '0,000.00'),
												    			maturityDate:	objIns.insList[i].maturityDate,
												    			status		:	objIns.insList[i].status,
												    		});
												}									
											}
										}
									});
									
								} else {
									Ext.ComponentMgr.get('insIssueNewColField').disable();
								}								
							}
							
							Ext.Ajax.request({
								url : 'queryDeal.action',
								params : {
									id : Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', combo.getValue())).get('id'),
								},
								success : function(response) {
									var objTwo = Ext.decode(response.responseText);
									var arrayLength = objTwo.deal.dealInstrumentMaps.length;
									for (var i = 0; i < arrayLength; i++) {
										Ext.data.StoreManager.lookup('tempCollateralStore').add(
									    		{
									    			dealCode:objTwo.deal.dealCode,
									    			instrumentType:objTwo.deal.dealInstrumentMaps[i].instrument.instrumentType.instrumentName,
									    			instrumentNo:objTwo.deal.dealInstrumentMaps[i].instrument.id,
									    			instrumentCode:objTwo.deal.dealInstrumentMaps[i].instrument.instrumentCode,
									    			value:objTwo.deal.dealInstrumentMaps[i].instrumentTransactions[0].transAmount,
									    			primaryDealer:objTwo.deal.dealInstrumentMaps[i].instrument.issuer.code,
									    			maturityDate:objTwo.deal.dealInstrumentMaps[i].instrument.maturityDate,
									    			status:objTwo.deal.dealInstrumentMaps[i].status,
									    			tempStatus:'old'
									    		});
									}
								}
							});
							
							Ext.data.StoreManager.lookup('tempCollateralStore').clearFilter(true);
							Ext.data.StoreManager.lookup('tempCollateralStore').filter('dealCode', combo.getValue());
						}
					}
				}
			}) ]
		},
		{
			xtype : 'label',
			html:'<br>'
		}, {
			xtype : 'label',
			id : 'insIssueMatDtLbl',
			style : 'font-weight:600;margin:15px 0 15px 0px;',

		},
		{
			xtype : 'label',
			html:'&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp'
		},
		{
			xtype : 'label',
			id : 'insIssueDealValLbl',
			//text:'Deal Value:',
			style : 'font-weight:600;margin:10px 0 0 0px;',
			//hidden:true,
		}]
	});
	
	Ext.Ajax.request({
		url : 'filterInitialDeals.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			var arrayLength = obj.deals.length;
			for (var i = 0; i < arrayLength; i++) {
				Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').add(
			    		{
			    			id:obj.deals[i].id,
			    			dealCode:obj.deals[i].dealCode,
			    			type:obj.deals[i].dealType.code,
			    			maturityDate:obj.deals[i].maturityDate,
			    			value:obj.deals[i].dealValue,
			    			whtCertStatus:obj.deals[i].withholdingCertificate,
			    		});
			}
			Ext.ComponentQuery.query('#newInsIssueTrType')[0].enable();
			Ext.ComponentQuery.query('#insIssueDealCombo')[0].enable();
		},
		failure : function(){
			Ext.Msg.alert('Error', 'Loading Deal List Failed!');
		}
	});
	
	return finalFieldSet;
};



InsIssueReceive.getFieldSet2 = function() {

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'Withholding Certificate Status',
		id : 'insIssueWithholdingCert',
		disabled : true,
		defaults : {
			anchor : '100%',
			flex: 1
		},
		defaultType: 'radiofield',
		layout: 'hbox',		
		items: [
			{
				boxLabel  : 'Not Available',
				name      : 'whtCertStatus',
				inputValue: 'No',
				id:'insIssueWithholdNo',
			}, {
				boxLabel  : 'Not Received',
				name      : 'whtCertStatus',
				inputValue: 'NotReceived',
				id:'insIssueWithholdNotReceived',
			}, {
				boxLabel  : 'Received',
				name      : 'whtCertStatus',
				inputValue: 'Received',
				id:'insIssueWithholdReceived',
			}
		]
	});
	return finalFieldSet;
};


InsIssueReceive.getFieldSet3 = function() {
	
	Ext.define('TempCollateral', {
		extend : 'Ext.data.Model',
		fields : [
		          {	name : 'dealCode',			type : 'string'	},
		          {	name : 'instrumentType',	type : 'string'	},
		          {	name : 'instrumentNo',		type : 'string'	},
		          {	name : 'instrumentCode',	type : 'string'	},
		          {	name : 'value',				type : 'float'	},
		          {	name : 'primaryDealer',		type : 'string'	},
		          {	name : 'maturityDate',		type : 'date',	dateFormat : 'c'	},
		          {	name : 'status',			type : 'string'	},
		          {	name : 'tempStatus',		type : 'string'	},
		          { name : 'tempValue',			type : 'float'	}
		         ]
	});

	var tempCollateralStore = new Ext.data.Store({
		model : 'TempCollateral',
		storeId : 'tempCollateralStore',
	});

	Ext.create('Ext.data.Store', {
		fields : [ 
					{	name : 'id',		type : 'int',		},
					{	name : 'type',		type : 'string',	},
					{	name : 'listed',	type : 'string',	},
					{	name : 'issuer',	type : 'string',	},
					{	name : 'scripts',	type : 'int',		},
					{	name : 'denominal',	type : 'int',	}
				],
		storeId:'insIssueReceiveInsTypeStore',
			});
	
	Ext.create('Ext.data.Store', {
		fields : [ 
					{	name : 'id',			type : 'int',		},
					{	name : 'code',			type : 'string',	},
					{	name : 'type',			type : 'string',	},
					{	name : 'issuer',		type : 'string',	},
					{	name : 'maturityDate',	type : 'date',		dateFormat : 'c'	},
					{	name : 'value',			type : 'string',	},
					{	name : 'status',		type : 'string',	}
				],
		storeId:'insIssueReceiveInsStore',
			});
	
	Ext.create('Ext.data.Store', {
		storeId:'insIssueReceiveIssuersStore',
		fields : [
		          {	name : 'id',			type : 'int',		},
		          {	name : 'name',			type : 'string',	},
		          {	name : 'code',			type : 'string',	},
		          {	name : 'creditRating',	type : 'string',	}
		         ]
	});
	
	Ext.Ajax.request({
		url : 'getIssuers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('insIssueReceiveIssuersStore').loadRawData(obj.issuerList);
		}
	});
	
	Ext.create('Ext.data.Store', {
		storeId:'insIssueReceivePrimaryDealersStore',
		fields : [ {
			name : 'id',
			type : 'int',
		},{
			name : 'name',
			type : 'string',
		},{
			name : 'code',
			type : 'string',
		},{
			name : 'creditRating',
			type : 'string',
		} ]
	});
	
	Ext.Ajax.request({
		url : 'getPrimaryDealers.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			Ext.data.StoreManager.lookup('insIssueReceivePrimaryDealersStore').loadRawData(obj.issuers);
		}
	});

	var finalFieldSet = Ext.create('Ext.form.FieldSet', {
		title : 'New Collateral Instrument',
		id : 'insIssueNewColField',
		disabled : true,
		defaults : {
			anchor : '100%'
		},
		items : [
			{
				xtype : 'label',
				id : 'insIssueValidInsCodeLbl',
				style : 'font-weight:600;margin:15px 0 15px 0px;font-color="red"',
			
			},
		{
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [
			Ext.create('Ext.form.ComboBox', {
		name : 'instrumentType',
		id : 'insIssueInstrumentType',
		fieldLabel : 'Instrument Type',
		store : Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore'), //instrumentTypes,
		queryMode : 'local',
		valueField : 'type',
		autoScroll : true,
		allowBlank : false,
		editable : false,
		flex : 1,
		padding : '0 5px 0 0',
		msgTarget : 'under',
		tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{type}</div>', '</tpl>'),
		displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{type}', '</tpl>'),
		listeners : {
			select : {
				fn : function(combo, value) {					
					var comboInsCode = Ext.ComponentQuery.query('#insIssueInsNo')[0];
					comboInsCode.clearValue();
					var prDealer = Ext.ComponentQuery.query('#insIssuePrimDealer')[0];
					var issuer = Ext.ComponentQuery.query('#insIssueIssuer')[0];
					var dfColMaturityDate = Ext.ComponentQuery.query('#insIssueColMatDate')[0];
					var cbInsNo = Ext.ComponentQuery.query('#insIssueInsNo')[0];
					var scriptable = Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('scripts');
					var haveDenominal = Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('denominal');
					var partialCmb = Ext.ComponentQuery.query('#insIssuePartialCb')[0];
					var denominalsCb = Ext.ComponentQuery.query('#insIssueDenominalsCb')[0];
					/*var partialAmnttf = Ext.ComponentQuery.query('#insIssuePartialValue')[0];*/
					console.log('SCRIPT:'+scriptable);
					console.log('DENOMINALS:'+haveDenominal);
					prDealer.clearValue();
					issuer.clearValue();
					//instrumentStore.clearFilter(true);
					var dealCombo = Ext.ComponentQuery.query('#insIssueDealCombo')[0];
					var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('type');
					/*if(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('listed')==='0'
						&& dealType==='RREPO'){*/
					if(dealType==='RREPO'){
						cbInsNo.setEditable(true);
						//Ext.data.StoreManager.lookup('insIssueReceiveInsStore').removeAll();
						//instrumentStore.filter('type', 'unlisted');
						dfColMaturityDate.enable();	
						if(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('issuer')==='G'){
							issuer.disable();
							prDealer.enable();
						}else{
							prDealer.disable();
							issuer.enable();
						}
					}else{						
						issuer.disable();
						//issuer.setEditable(false);
						prDealer.disable();
						dfColMaturityDate.disable();
						cbInsNo.setEditable(false);
						/*if(dealType==='RREPO'){
							console.log('RREPO Instrument loading');
						}else{
							Ext.Ajax.request({
								url : 'getCollaterals',
								params : {
									queryOne : Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('dealCode'),
									queryTwo : dealType,
								},
								success : function(response) {
									var objIns = Ext.decode(response.responseText);
									if(objIns.insList!=null){
										var arrayLength = objIns.insList.length;
										for (var i = 0; i < arrayLength; i++) {
											Ext.data.StoreManager.lookup('insIssueReceiveInsStore').add(
										    		{
										    			id			:	objIns.insList[i].id,
										    			code		:	objIns.insList[i].instrumentCode,
										    			type		:	objIns.insList[i].instrumentType.instrumentName,
										    			issuer		:	objIns.insList[i].issuer.code,
										    			maturityDate:	objIns.insList[i].maturityDate,
										    			status		:	objIns.insList[i].status,
										    		});
										}									
									}
								}
							});
						}*/
						//console.log(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('id', combo.getValue())).get('type'));
						
					}
					
					if(haveDenominal==1){
						denominalsCb.setValue(true);
					}else{
						denominalsCb.setValue(false);
					}
					if((scriptable==0)||(scriptable==1 && haveDenominal==1)){
						partialCmb.enable();
						/*partialAmnttf.reset();*/
					}else{
						partialCmb.reset();
						partialCmb.disable();
						/*partialAmnttf.reset();
						partialAmnttf.disable();*/
					}
					
					Ext.data.StoreManager.lookup('insIssueReceiveInsStore').clearFilter();
					var tempInsType = Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('type');
					
					Ext.data.StoreManager.lookup('insIssueReceiveInsStore').filter([
					        {filterFn: function(item) { return item.get("type")===tempInsType; }}
					    ]);
					//Ext.data.StoreManager.lookup('insIssueReceiveInsStore').filter('type', Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', combo.getValue())).get('type'));
					//comboInsCode.bindStore(instrumentStore);
					//comboInsCode.show();
				}
			}
		}
		
	}),
	Ext.create('Ext.form.ComboBox', {
							fieldLabel : 'Instrument Code',
							store : Ext.data.StoreManager.lookup('insIssueReceiveInsStore'), //instrumentStore,
							valueField : 'code',
							displayField : 'code',
							id : 'insIssueInsNo',
							autoScroll : true,
							queryMode : 'local',
							allowBlank : false,
							msgTarget : 'under',
							editable : true,
							flex : 1,
							padding : '0 5px 0 0',
						/*	tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
							displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>'),*/
							listeners : {
								select : {
									fn : function(combo, value) {
										var repInsCmb = Ext.ComponentQuery.query('#insIssueInstrumentType')[0];
										var repPrimaryDealer = Ext.ComponentQuery.query('#insIssuePrimDealer')[0];
										var repIssuerCB = Ext.ComponentQuery.query('#insIssueIssuer')[0];
										console.log(repInsCmb.getValue());
										if(repInsCmb.getValue()==null){
											Ext.Msg.alert('Error', 'Please select an Instrument Type First!');
											combo.clearValue();
										}else{
											if(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsTypeStore').find('type', repInsCmb.getValue())).get('issuer')==='G'){
												repPrimaryDealer.setValue(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', combo.getValue())).get('issuer'));
												repIssuerCB.clearValue();
											}else{
												repIssuerCB.setValue(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', combo.getValue())).get('issuer'));
												repPrimaryDealer.clearValue();
											}
											
											Ext.ComponentQuery.query('#insIssueInsValue')[0].setValue(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', combo.getValue())).get('value'));										

											var dfColMaturityDate = Ext.ComponentQuery.query('#insIssueColMatDate')[0];
											dfColMaturityDate.setValue(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', combo.getValue())).get('maturityDate'));
											dfColMaturityDate.disable();
										}
									}
								},
								blur: function (combo){							        
							        if(combo.editable){							        	
							        	if(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').findRecord('code', combo.getValue())==null){
							        		Ext.Ajax.request({
												url : 'validInsCode.action',
												params : {
													querry : combo.getValue(),
												},
												success : function(response) {
													var validCode = Ext.decode(response.responseText);
													if(validCode.success){
														Ext.ComponentQuery.query('#insIssueValidInsCodeLbl')[0].setText(combo.getValue()+' Already Exists!');
														combo.clearValue();
													}else{
														Ext.ComponentQuery.query('#insIssueValidInsCodeLbl')[0].setText('');
													}
												},
												failure : function(){
													Ext.ComponentQuery.query('#insIssueValidInsCodeLbl')[0].setText('<font color="red">Cannot Validate Code!</font>');
												}
										
											});
							        	}   	
									}else{
										Ext.ComponentQuery.query('#insIssueValidInsCodeLbl')[0].setText('');
									}							   
							    }
							}
						})
						 ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ 	 Ext.create('Ext.form.ComboBox', {
				name : 'issuer',
				fieldLabel : 'Issuer',
				store : Ext.data.StoreManager.lookup('insIssueReceiveIssuersStore'),
				valueField : 'code',
				autoScroll : true,
				flex : 1,
				queryMode : 'local',
				padding : '0 5px 0 0',
				style:'margin-top:5px;',
				id : 'insIssueIssuer',
				allowBlank : false,
				msgTarget : 'under',
				editable : true,
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
			}),
						 Ext.create('Ext.form.ComboBox', {
								fieldLabel : 'Primary Dealer',
								store : Ext.data.StoreManager.lookup('insIssueReceivePrimaryDealersStore'),
								valueField : 'code',
								id : 'insIssuePrimDealer',
								autoScroll : true,
								queryMode: 'local',
								//editable : false,
								flex : 1,
								padding : '0 5px 0 0',
								style:'margin-top:5px;',
								tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{name}</div>', '</tpl>'),
								displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{name}', '</tpl>')
							})
						]
		}, 		{
					xtype : 'fieldcontainer',
					layout : 'hbox',
					items : [ 
							{
								xtype : 'datefield',
								fieldLabel : 'Maturity Date',
								id : 'insIssueColMatDate',
								allowBlank : false,
								flex : 1,
								padding : '0 5px 0 0',
								style:'margin-top:5px;',
								format : 'd/m/Y',
								emptyText : 'dd/mm/yyyy',
								minValue : new Date(),
							},
							{
								xtype : 'textfield',
								minValue : 0,
								name : 'insValue',
								padding : '0 5 0 0',
								allowBlank : false,
								//style:'margin-top:10px;',
								id : 'insIssueInsValue',
								fieldLabel : 'Value',
								disabled : true,
								flex : 1,
								fieldStyle : "text-align:right;",
								maskRe : /[\d\,.]/,
								listeners : {
									blur : function() {
										this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
									},
									render : function() {
										this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
									}
								}
							}
					]
				},
				{
					xtype : 'fieldcontainer',
					layout : 'hbox',
					items : [ 
							{								
								xtype : 'checkboxfield',
								boxLabel : 'Denominals',
								inputValue : true,
								id : 'insIssueDenominalsCb',
								disabled : true,
								flex : 1,
								padding : '0 5 0 0',
							},
							{								
								xtype : 'checkboxfield',
								boxLabel : 'Partial',
								name : 'partial',
								inputValue : true,
								id : 'insIssuePartialCb',
								disabled : true,
								flex : 1,
								padding : '0 5 0 0',
								listeners : {
									change : function(field, newVal) {
										if(newVal){
											Ext.ComponentQuery.query('#insIssueInsValue')[0].enable();
										}else{
											var valField = Ext.ComponentQuery.query('#insIssueInsValue')[0];
											var dealCmb = Ext.ComponentQuery.query('#insIssueInsNo')[0];
											valField.disable();
											valField.setValue(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', dealCmb.getValue())).get('value'));
							
											
										}
									}
								}			
							},
							/*{
								xtype : 'textfield',
								minValue : 0,
								name : 'partialValue',
								padding : '0 5 0 0',
								id : 'insIssuePartialValue',
								fieldLabel : 'Partial Amount',
								flex : 1,
								disabled : true,
								maskRe : /[\d\,.]/,
								listeners : {
									blur : function() {
										this.setRawValue(Ext.util.Format.number(this.value.replace(/,/g, ''), '0,000.0000'));
									},
									render : function() {
										this.setRawValue(Ext.util.Format.number(this.value, '0,000.0000'));
									}
								}
							}*/
					]
				}
		,
		{
			xtype : 'button',
			text : 'Add',
			id : 'insIssueRepoAddColBtn',
			// flex : 1,
			anchor:'10%',
			padding : '0 7px 0 0',
			//width : '32px',
			handler : function(btn) {
				
				var dealCombo = Ext.ComponentQuery.query('#insIssueDealCombo')[0];
				//console.log(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('type'));
				var dealMatdate = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('maturityDate');

				var newColMatDate = Ext.ComponentQuery.query('#insIssueColMatDate')[0];
				var cbInsType = Ext.ComponentQuery.query('#insIssueInstrumentType')[0];
				var tfInsNo = Ext.ComponentQuery.query('#insIssueInsNo')[0];
				var tfInsVal = Ext.ComponentQuery.query('#insIssueInsValue')[0];
				//var cbPrimaryDealer = Ext.ComponentQuery.query('#insIssuePrimDealer')[0];
				var partialCmb = Ext.ComponentQuery.query('#insIssuePartialCb')[0];
				/*var partialAmnttf = Ext.ComponentQuery.query('#insIssuePartialValue')[0];*/
				
				var trTypeCmb = Ext.ComponentQuery.query('#newInsIssueTrType')[0];


				if(trTypeCmb.getValue()==='Exchange'){
					if(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('type') == 'REPO'){
						colStatus='Issued by Custodian';
					}else{
						colStatus='Received From Customer';
					}					
				}else{
					if(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('type') == 'REPO'){
						colStatus='Issued by Custodian';
					}else{
						colStatus='Received From Customer';
					}
				}

				if(trTypeCmb.getValue()==null){
					Ext.MessageBox.alert('Error', 'Please Select a Transaction Type.');
				}else if (cbInsType.getValue() == null) {
					Ext.MessageBox.alert('Error', 'Please select an Instrument type.');
				} else if (tfInsNo.getValue() == '') {
					Ext.MessageBox.alert('Error', 'Please enter the Instrument Number.');
				} else if (tfInsVal.getValue() == 0 || tfInsVal.getValue() == null) {
					Ext.MessageBox.alert('Error', 'Please check the Instrument Value.');
				} else if (partialCmb.getValue() && (tfInsVal.getValue().trim()==='')) {
					Ext.MessageBox.alert('Error', 'Please enter the Partial Amount.');
				} else {
					/*var partialAmnt = '0';
					if(partialCmb.getValue()){
						partialAmnt = partialAmnttf.getValue();
					}*/
					if (newColMatDate.getValue() < dealMatdate) {
						Ext.Msg.confirm('Confirm Box', 'Collateral Matures too early! Do you wish to continue?', function(buttonText) {
							if (buttonText == "yes") {
								var recordIndex = tempCollateralStore.findBy(function(record, id) {
									if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
										return true;
									}
									return false;
								});
								if (recordIndex != -1) {
									Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
								} else {
									var userco = Ext.ModelManager.create({
										dealCode:dealCombo.getValue(),
										instrumentType : cbInsType.getValue(),
										instrumentNo : tfInsNo.getValue(),
										instrumentCode :  tfInsNo.getValue(), //Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('id', tfInsNo.getValue())).get('code'),
										value : tfInsVal.getValue(),
										primaryDealer : Ext.ComponentQuery.query('#insIssueIssuer')[0].getValue(), //  Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', tfInsNo.getValue())).get('issuer'),
										maturityDate : newColMatDate.getValue(),
										status : colStatus,
										tempStatus : 'new'
									}, 'TempCollateral');
									tempCollateralStore.add(userco);
									
									Ext.data.StoreManager.lookup('insIssueReceiveInsStore').remove(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('id', tfInsVal.getValue()));//ssssttt
									
									Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0].getView().refresh();
									var pagingToolbar = Ext.ComponentQuery.query('#insIssueRepoColGridToolBar')[0];
									tempCollateralStore.totalCount = tempCollateralStore.count();
									pagingToolbar.onLoad();
									tempCollateralStore.commitChanges();
									Ext.each(btn.up('fieldset').query('field'), function(field) {
									    field.reset();
									});
								}
							}
						});
					} else {
						var recordIndex = tempCollateralStore.findBy(function(record, id) {
							if (record.get('instrumentType') === cbInsType.getValue() && record.get('instrumentNo') === tfInsNo.getValue()) {
								return true;
							}
							return false;
						});
						if (recordIndex != -1) {
							Ext.MessageBox.alert('Error!', 'Duplicate Entry!!!');
						} else {
							var userco = Ext.ModelManager.create({
								dealCode:dealCombo.getValue(),
								instrumentType : cbInsType.getValue(), // Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('id', tfInsNo.getValue())).get('type'),
								instrumentNo : tfInsNo.getValue(),
								instrumentCode :  tfInsNo.getValue(), //Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('id', tfInsNo.getValue())).get('code'),
								value : tfInsVal.getValue(),
								primaryDealer : Ext.ComponentQuery.query('#insIssueIssuer')[0].getValue(),  //Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', tfInsNo.getValue())).get('issuer'),
								maturityDate : newColMatDate.getValue(),
								status : colStatus,
								tempStatus : 'new'
							}, 'TempCollateral');
							tempCollateralStore.add(userco);
							//Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('id', tfInsNo.getValue()));
							Ext.data.StoreManager.lookup('insIssueReceiveInsStore').remove(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveInsStore').find('code', tfInsNo.getValue())));
							Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0].getView().refresh();
							var pagingToolbar = Ext.ComponentQuery.query('#insIssueRepoColGridToolBar')[0];
							tempCollateralStore.totalCount = tempCollateralStore.count();
							pagingToolbar.onLoad();
							tempCollateralStore.commitChanges();
							Ext.each(btn.up('fieldset').query('field'), function(field) {
							    field.reset();
							});
						}
					}
				}
			}
		}
		]
	});
	return finalFieldSet;
};

//Ext.data.StoreManager.lookup('tempCollateralStore').filter('dealCode', 'none');

InsIssueReceive.getFieldSet4 = function() {
	return Ext.create('Ext.grid.Panel', {
		id : 'insIssueRepoCollateralPanel',
		store : Ext.data.StoreManager.lookup('tempCollateralStore'),
		title : 'Instruments List',
		style : 'margin-top:10px;',
		disabled:true,
		features: [{
	        ftype: 'summary'
	    }],
		columns : [ {
			text : 'Type',
			dataIndex : 'instrumentType',
			flex : 4
		}, {
			text : 'Code',
			dataIndex : 'instrumentCode',
			flex : 7
		}, {
			text : 'Maturity',
			dataIndex : 'maturityDate',
			xtype : 'datecolumn',
			format : 'd-m-Y',
			flex : 6
		}, {
			text : 'Value',
			dataIndex : 'value',
			xtype : 'numbercolumn',
			format : '0,000.00',
			align : 'right',
			flex : 9,
			summaryType : 'sum',
			summaryRenderer : function(value, summaryData, dataIndex) {
				var val = Ext.util.Format.number(value, '0,000.00');
				return Ext.String.format('<B>Total</B>\t{0}', val); 
			},
		}, {
			text : 'Status',
			dataIndex : 'status',
			flex : 11,
			align : 'right',
		}

		],
		height : 300,
		width : 450,
		dockedItems : [ {
			xtype : 'pagingtoolbar',
			id : 'insIssueRepoColGridToolBar',
			store : Ext.data.StoreManager.lookup('tempCollateralStore'),
			dock : 'bottom',
			displayInfo : true
		} ],
		bbar : [ '->', 		         
		  {
				text : 'Next State',
				id : 'insIssueNextBtn',
				disabled:true,
				handler : function(btn) {
					var nextStatus='Error';
					var tempValue = 0;
					var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
					var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type');
					var trTypeCmb = Ext.ComponentQuery.query('#newInsIssueTrType')[0];
					var trType = trTypeCmb.getValue();
					var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];				
					var sm = pCpnDtStorePanel.getSelectionModel();
					var sel = sm.getSelection();
					var curStatus = sel[0].get('status');				

	
					if(((dealType === 'PURCH')&&(curStatus.match(/Matured.*/)))
							||((dealType === 'RREPO')&&(curStatus==='Dispatched To Customer'))
							||((dealType === 'SALE')&&(curStatus==='Dispatched To Customer'))
							||((dealType === 'REPO')&&(curStatus==='Dispatched To Custodian'))){
						
						alert('Cannot Change Status! Invalid Action!');
						return false;
					}					
					if(curStatus==='Not Received From Customer'){
						if (confirm("Received From Customer?") == true) {
							nextStatus = 'Received From Customer';
						}else{
							nextStatus='Error';
						}
						
					}else if(curStatus==='Received From Customer'){
						if (confirm("Dispatched to Custodian?") == true) {
							nextStatus = 'Dispatched to Custodian';
						}else{
							nextStatus='Error';
						}
						
					}else if(curStatus==='Dispatched to Custodian'){
						if(dealType === 'PURCH'){
							if (confirm("Do you wish to Mature the Instrument early?") == true) {
								//nextStatus = 'Matured Early'; //removed due to seperate maturity screen
								alert('Short Maturity is not allowed!.');
							}else{
								nextStatus='Error';
							}
						}else if(dealType === 'RREPO'){
							if(trType === 'Exchange'){
								var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('value');
								var Bal = pCpnDtStorePanel.store.sum('value')-sel[0].get('value');
								if(Bal<dealVal*1.1){
									alert('Not Enough Balance!');
									nextStatus='Error';
								}else{
									if (confirm("Status will changed to 'Exchanged-Out From Custodian'") == true) {
										nextStatus = 'Exchanged-Out From Custodian';
										sel[0].set('value', 0);
										sel[0].commit();
									}else{
										nextStatus='Error';
									}
								}
							}else{
								if(new Date()<Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('maturityDate')){
									alert('Cannot issue before Deal Maturity!');
									nextStatus='Error';
								}else{
									if (confirm("Status will changed to 'Not Issued by Custodian'") == true) {
										nextStatus='Not Issued by Custodian';
									}else{
										nextStatus='Error';
									}
									
								}	
							}
						}else{
							alert('Cannot Change Status! Invalid Action!');
							nextStatus='Error';
						}						
					}else if(curStatus==='Issued by Custodian'){						
						if (confirm("Status will changed to 'Dispatched to Customer'") == true) {
							nextStatus = 'Dispatched to Customer';
						}else{
							nextStatus='Error';
						}
						
					}else if(curStatus==='Dispatched to Customer'){
						if(dealType === 'REPO'){							
							if(trType === 'Exchange'){
								var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('value');
								var Bal = pCpnDtStorePanel.store.sum('value')-sel[0].get('value');
								if(Bal<dealVal*1.1){
									alert('Not enough Balance!');
									nextStatus='Error';
								}else{
									if (confirm("Continue Exchange?") == true) {
										nextStatus = 'Exchanged-IN From Customer';
										sel[0].set('tempValue', sel[0].get('value'));
										sel[0].set('value', 0);
										sel[0].commit();
									}else{
										console.log('898 error');
										nextStatus='Error';
									}
								}								
							}else{
								if(new Date()<Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('maturityDate')){
									alert('Cannot issue before Deal Maturity!');
									nextStatus='Error';
								}else{
									if (confirm("Status will changed to 'Not Received From Customer'") == true) {
										nextStatus = 'Not Received From Customer';
									}else{
										nextStatus='Error';
									}
								}								
							}
						}else{
							alert('Cannot Change Status! Invalid Action!');
							console.log('910 error');
							nextStatus='Error';
						}
					}else if(curStatus==='Not Issued by Custodian'){
						if (confirm("Status will changed to 'Issued by Custodian'") == true) {
							nextStatus = 'Issued by Custodian';
						}else{
							nextStatus='Error';
						}
						
					}else if(curStatus==='Exchanged-Out From Custodian'){
						if(dealType === 'RREPO'){
							if(trType === 'Exchange'){								
								if (confirm("Status will changed to 'Exchanged-Out To Customer'") == true) {
									nextStatus = 'Exchanged-Out To Customer';
								}else{
									nextStatus='Error';
								}								
							}else{
								alert('Cannot Change Status! Invalid Action!');
								nextStatus='Error';
							}
						}			
					}else if(curStatus==='Exchanged-IN From Customer'){
						if(dealType === 'REPO'){
							if(trType === 'Exchange'){								
								if (confirm("Status will changed to 'Exchanged-IN To Custodian'") == true) {
									nextStatus = 'Exchanged-IN To Custodian';
								}else{
									nextStatus='Error';
								}								
							}else{
								alert('Cannot Change Status! Invalid Action!');
								nextStatus='Error';
							}
						}			
					}else if(curStatus==='Not Received From Custodian'){
						if(dealType=='SALE'){
							if (confirm("Status will changed to 'Issued by Custodian'") == true) {
								nextStatus = 'Issued by Custodian';
							}else{
								nextStatus='Error';
							}
						}else{
							alert('Cannot Change Status! Invalid Action!');
							nextStatus='Error';
						}
					}else{
						alert('Cannot Change Status! Invalid Action!');
						nextStatus='Error';
					}

					if(nextStatus==='Error'){
						console.log('Error!');
					}else{
						sel[0].set('status', nextStatus);
						sel[0].set('tempStatus', 'modified');
						sel[0].commit();
					}
				}
			},     
		 
/*		{
			text : 'Receive',
			id : 'insIssueReceiveBtn',
			disabled:true,
			handler : function() {
				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
				var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];

				var sm = pCpnDtStorePanel.getSelectionModel();
				var sel = sm.getSelection();
				
				var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type');
				if(dealType === 'REPO'){
					if(new Date()<Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('maturityDate')){
						Ext.MessageBox.alert('Error', 'Cannot receive before Deal Maturity!');
					}else{
						sel[0].set('status', 'Received');
						sel[0].commit();
					}
					
				}else{
					sel[0].set('status', 'Received');
					sel[0].commit();					
				}
			}
		}, {
			text : 'Issue',
			id : 'insIssueIssueBtn',
			disabled:true,
			handler : function() {
				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
				var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];

				var sm = pCpnDtStorePanel.getSelectionModel();
				var sel = sm.getSelection();
				
				var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type');
				if(dealType === 'RREPO'){
					if(new Date()<Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('maturityDate')){
						Ext.MessageBox.alert('Error', 'Cannot Issue before Deal Maturity!');
					}else{
						sel[0].set('status', 'Issued');
						sel[0].commit();
					}
					
				}else{
					sel[0].set('status', 'Issued');
					sel[0].commit();					
				}
			}
		}, {
			text : 'Ex-OUT',
			id : 'insIssueExOutBtn',
			disabled:true,
			handler : function() {
				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
				var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];
				var sm = pCpnDtStorePanel.getSelectionModel();
				var sel = sm.getSelection();
				//sel[0].set('status', 'Exchanged-OUT');
				//console.log('SUM:'+pCpnDtStorePanel.store.sum('value'));
				if(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type') === 'RREPO'){
					var dealCombo = Ext.ComponentQuery.query('#insIssueDealCombo')[0];
					var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('value');
					var Bal = pCpnDtStorePanel.store.sum('value')-sel[0].get('value');
					if(Bal<dealVal*1.1){
						Ext.MessageBox.alert('Error', 'Not enough Balance!');
					}else{
						sel[0].set('status', 'Exchanged-OUT');
						//var val = sel[0].get('value')*(-1);
						sel[0].set('value', 0);
						sel[0].commit();						
					}					
				}else{
					sel[0].set('status', 'Exchanged-OUT');
					sel[0].commit();				
				}
			}
		}, {
			text : 'Ex-IN',
			id : 'insIssueExInBtn',
			disabled:true,
			handler : function() {
				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
				var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];
				var sm = pCpnDtStorePanel.getSelectionModel();
				var sel = sm.getSelection();
				//sel[0].set('status', 'Exchanged-IN');
				if(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type') === 'REPO'){
					var dealCombo = Ext.ComponentQuery.query('#insIssueDealCombo')[0];
					var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealCombo.getValue())).get('value');
					var Bal = pCpnDtStorePanel.store.sum('value')-sel[0].get('value');
					if(Bal<dealVal*1.1){
						Ext.MessageBox.alert('Error', 'Not enough Balance!');
					}else{
						sel[0].set('status', 'Exchanged-IN');
						//var val = sel[0].get('value')*(-1);
						sel[0].set('value', 0);
						sel[0].commit();						
					}					
				}else{
					sel[0].set('status', 'Exchanged-IN');
					sel[0].commit();				
				}
			}
		}*/,
		{
			text : 'Remove',
			id : 'insIssueRemoveBtn',
			disabled:true,
			handler : function() {

				var collateralsStore = Ext.data.StoreManager.lookup('tempCollateralStore');
				var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];

				var sm = pCpnDtStorePanel.getSelectionModel();
				var sel = sm.getSelection();

				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
				var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('value');
				var Bal = pCpnDtStorePanel.store.sum('value')-sel[0].get('value');
				if(Bal<dealVal*1.1){
					alert('Not enough Balance!');
					nextStatus='Error';
				}else{
					if (confirm("Continue to Remove?") == true) {
						pCpnDtStorePanel.store.remove(sel[0]);
				
						Ext.data.StoreManager.lookup('insIssueReceiveInsStore').add(
					    		{
					    			id			:	sel[0].get('instrumentNo'),
					    			code		:	sel[0].get('instrumentCode'),
					    			type		:	sel[0].get('instrumentType'),
					    			issuer		:	sel[0].get('primaryDealer'),
					    			value		:	sel[0].get('value'),
					    			maturityDate:	sel[0].get('maturityDate'),
					    			status		:	sel[0].get('status'),
					    		});
					}
				}

				Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0].getView().refresh();

				var pagingToolbar = Ext.ComponentQuery.query('#insIssueRepoColGridToolBar')[0];
				collateralsStore.totalCount = collateralsStore.count();
				pagingToolbar.onLoad();
			}
		} ],
		listeners : {
			itemclick : function(dv, record, item, index, e) {
				var nextBtn = Ext.ComponentMgr.get('insIssueNextBtn');
/*				var receiveBtn = Ext.ComponentMgr.get('insIssueReceiveBtn');
				var issueBtn = Ext.ComponentMgr.get('insIssueIssueBtn');
				var exOutBtn = Ext.ComponentMgr.get('insIssueExOutBtn');
				var exInBtn = Ext.ComponentMgr.get('insIssueExInBtn');*/
				var removeBtn = Ext.ComponentMgr.get('insIssueRemoveBtn');
				var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');

				var recStatus = record.get('status');

				if(record.get('tempStatus') === 'new'){
					removeBtn.enable();					
				}else{
					removeBtn.disable();
				}
				
				dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type');
				
				if(((dealType === 'PURCH')&&(recStatus.match(/Matured.*/)))
						||((dealType === 'RREPO')&&(recStatus==='Dispatched To Customer'))
						||((dealType === 'SALE')&&(recStatus==='Dispatched To Custodian'))
						||((dealType === 'REPO')&&(recStatus==='Dispatched To Custodian'))){
					
					nextBtn.disable();
				}else{
					nextBtn.enable();
				}
			}
		}
	});
};

InsIssueReceive.getCenterPanel = function() {
	var filedset1 = InsIssueReceive.getFieldSet1();
	var filedset2 = InsIssueReceive.getFieldSet2();
	var filedset3 = InsIssueReceive.getFieldSet3();
	var filedset4 = InsIssueReceive.getFieldSet4();

	var formPanel = Ext.create('Ext.form.FormPanel', {
		id : 'insIssueReceivePanel',
		bodyPadding : '20',
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 175,
			anchor : '72%',
		},
		fieldDefaults : {
			labelAlign : 'left',
			labelWidth : 150,
		},
		title : 'Receive, Issue, Exchange Collaterals',
		items : [ filedset1, filedset2, filedset3, filedset4 ],
		buttonAlign : 'center',
		buttons : [
		{
			text : 'Save',
			id : 'insIssueReceiveSaveBtn',
			itemId : 'saveButton',
			handler : function() {
				var form = this.up('form').getForm();
				Ext.ComponentMgr.get('insIssueNewColField').disable();
			
				form.url = 'insIssueReceive.action';
				if (form.isValid()) {
					formPanel.setLoading('Saving...');
					var insTrList = '';
					Ext.data.StoreManager.lookup('tempCollateralStore').each(function(r) {
						if(r.get('value')!=0)
							insTrList += r.get('instrumentType')+','+r.get('instrumentCode')+','+r.get('value')+','+r.get('primaryDealer')+','+Ext.util.Format.date(r.get('maturityDate'))+','+r.get('status')+','+r.get('tempStatus')+';';
						
						if(r.get('value')==0 && r.get('tempStatus')=='modified')
							insTrList += r.get('instrumentType')+','+r.get('instrumentCode')+','+r.get('tempValue')+','+r.get('primaryDealer')+','+Ext.util.Format.date(r.get('maturityDate'))+','+r.get('status')+','+r.get('tempStatus')+';';
						});
					
					
					var dealIdCmb = Ext.ComponentMgr.get('insIssueDealCombo');
					var dealType = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('type');
					if(dealType==='REPO' || dealType==='RREPO'){						
						var pCpnDtStorePanel = Ext.ComponentQuery.query('#insIssueRepoCollateralPanel')[0];	
						var dealVal = Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').getAt(Ext.data.StoreManager.lookup('insIssueReceiveDealsStore').find('dealCode', dealIdCmb.getValue())).get('value');
						var Bal = pCpnDtStorePanel.store.sum('value');
						if(Bal>=dealVal*1.10){
							form.submit({						
								params : {
									'user'			:	'InsIssueRecUser',
									'insTrList'		:	insTrList,
								},
								success : function(form, action) {
									form.reset();
									Ext.Msg.alert('Success', '<b>'+action.result.dealCode+'</b> deal Instruments Updated.');
									Ext.ComponentQuery.query('#insIssueMatDtLbl')[0].setText('');
									Ext.ComponentQuery.query('#insIssueDealValLbl')[0].setText('');
									Ext.data.StoreManager.lookup('tempCollateralStore').removeAll();
									formPanel.setLoading(false);
								},
								failure : function(form, action) {
									Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>'+action.result.status);
									formPanel.setLoading(false);
								}
							});
							
						}else{
							Ext.Msg.alert('Not Enough Collateral Value!', 'Collateral Values must be atleast 110% of the Deal Value ('+dealVal*1.10+')');
							Ext.ComponentMgr.get('insIssueNewColField').enable();
							
							var tempColStr = Ext.data.StoreManager.lookup('tempCollateralStore');
							tempColStr.each(function(rec){
						        Ext.data.StoreManager.lookup('insIssueReceiveInsStore').add(
						          		{
        					    			id			:	rec.get('instrumentNo'),
        					    			code		:	rec.get('instrumentCode'),
        					    			type		:	rec.get('instrumentType'),
        					    			issuer		:	rec.get('primaryDealer'),
        					    			value		:	rec.get('value'),
        					    			maturityDate:	rec.get('maturityDate'),
        					    			status		:	rec.get('status'),
        					    		});
						    });
							tempColStr.removeAll();							
							formPanel.setLoading(false);
						}						
					}else{
						form.submit({						
							params : {
								'user'			:	'InsIssueRecUser',
								'insTrList'		:	insTrList,
							},
							success : function(form, action) {
								form.reset();
								Ext.Msg.alert('Success', '<b>'+action.result.dealCode+'</b> deal Instruments Updated.');
								Ext.ComponentQuery.query('#insIssueMatDtLbl')[0].setText('');
								Ext.ComponentQuery.query('#insIssueDealValLbl')[0].setText('');
								Ext.data.StoreManager.lookup('tempCollateralStore').removeAll();
								formPanel.setLoading(false);
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', 'There is some error returned from the server.<br>'+action.result.status);
								formPanel.setLoading(false);
							}
						});
					}				
					
				
				}else{
					Ext.Msg.alert("Form Incomplete. Please check!");
				}
			}
		
		},
		{
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				App.Core.setScreen(InsIssueReceive.getCenterPanel());
			}
		}
		 ]
	});
	
	return formPanel;
};
